from django.shortcuts import render,HttpResponse
from readJineng.models import Exam_jineng,Exam_jinengForm
import os,xlrd
import docx
import json
from readxls.models import Exam,Kaoti,KaotiForm
from lilun.models import Lilun,LilunForm

def writeToDB(docxpath):
    basename = os.path.basename(docxpath)  # 获取文件名
    title =  basename
    content = ''
    document = docx.Document(docxpath)
    # print('=========',path)

    for para in document.paragraphs:
        content += '\n' + para.text
        # content +=  para.text
    # print(content)

    Exam_jineng(title=title,title_content=content).save()

def query(path):#获取所有存放word文件的路径
    all_docx_paths = []
    for i in os.walk(path):
        # print(i)
        if len(i[1])==0:
            for j in i[2]:
                print(j)
                if j.strip().endswith('.docx') and bool(j.find('人工智能')+1):
                    all_docx_paths.append(os.path.join(i[0],j))
    for i in all_docx_paths:
        writeToDB(i)
        print(i)
        # break
    return all_docx_paths
# Create your views here.
#读取数据并存储
def readjineng(request):
    docxpath = r'C:\Users\gao10\Desktop\201811考题'
    query(docxpath)   #读取数据并存储
    return HttpResponse('更新成功')

#显示界面
def showjineng(request):
    if request.method == 'GET':
        # readjineng(request)
        jineng = Exam_jinengForm()
        lilun = LilunForm()
        kaotiform = KaotiForm()
        return render(request,'readjineng/showExams_jineng.html',locals())
    else:
        post = request.POST
        print('post:',post)
        Exams_jineng_id = post.get('id').strip()
        print('======Exams_jineng_id',Exams_jineng_id)

        Exams_jinengs = list(Exam_jineng.objects.filter(id = Exams_jineng_id).values())
        print(Exams_jinengs)

        return HttpResponse(json.dumps(Exams_jinengs))

def showjineng1(request):
    get = request.GET
    id = get.get('id','none').strip()
    if id=='none':
        return render(request,'readjineng/showExams_jineng1.html',locals())
    else:
        id = int(id)
        print('id:',id)
        exam_jineng = Exam_jineng.objects.get(id=id)
        print(exam_jineng)
        return render(request, 'readjineng/showExams_jineng1.html', {'exam_jineng':exam_jineng,'display':'pre{display: block;}'})
